package com.woniu.sharepark.config;


import com.woniu.sharepark.leasesystem.common.constant.SystemConstant;
import com.woniu.sharepark.leasesystem.lessor.dao.CarParkDAO;
import com.woniu.sharepark.leasesystem.lessor.pojo.CarPark;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author DELL
 * @date 2019/6/18 16:54
 * version v1.0
 */
@Component
public class RedisSubscribeThread implements CommandLineRunner {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private CarParkDAO carParkDAO;
    @Override
    public void run(String... strings) throws Exception {
        redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.pSubscribe(new MessageListener() {
                    @Override
                    public void onMessage(Message message, byte[] pattern) {

                        System.out.println(message);
                        String mesg = String.valueOf(message);
                        if (mesg.contains(":")){
                            String[] carparks = mesg.split(":");
                            SystemConstant.CARPARK_STATUS="未租";
                            String carpark = carparks[carparks.length-1];
                            CarPark carPark = carParkDAO.selectByPrimaryKey(Integer.parseInt(carpark));
                            if (carPark.getcState().equals("已租")){
                                return;
                            }
                            carParkDAO.updateStatus(SystemConstant.CARPARK_STATUS,Integer.parseInt(carpark));
                            //业务处理
                        }


                    }
                },"*@0*".getBytes());
                return null;
            }
        });
    }

}